<!--
 * @Descripttion: 编辑器
 * @Author: Leeym
 * @Date: 2020/10/19 15:24
-->
<template>
  <div :id="editorId"></div>
</template>

<script>
import Editor from "wangeditor";
import emojiJSON_qq from "./emoji-qq.json";
import emojiJSON_sina from "./emoji-sina.json";
// import { sm2Decrypt } from "@/utils/sm2CryptoMethods";
// import { aesEncrypt } from "@/utils/cryptoMethods";
import { Loading } from "element-ui";
// import upLoadHeaderParams from "@/mixins/upLoadHeaderParams";
import AlertMenu from "./components/textIndent";
export default {
  name: "Editor",
  // mixins: [upLoadHeaderParams],
  props: {
    editorId: {
      type: String,
      default: "editor",
    },
    uploadImgPath: {
      type: String,
      default: "",
    },
    uploadVideoPath: {
      type: String,
      default: "",
    },
    isPreviewContent: {
      // 是否只预览编辑器内容，无需操作菜单
      type: Boolean,
      default: false,
    },
    height: {
      // 设置编辑区域高度为 300px
      type: Number,
      default: 300,
    },
  },
  data() {
    return {
      editor: null,
    };
  },
  mounted() {
    this.configurationEditor();
  },
  beforeDestroy() {
    // 销毁编辑器
    this.editor.destroy();
    this.editor = null;
  },
  methods: {
    headersParams() {
      return {
        // Authorization: this.Authorization,
        // platform: "PC",
        // "X-Time": (new Date().getTime() / 1000).toFixed(0),
        // "x-Nonce": aesEncrypt(new Date().getTime() + getUid(16)),
      };
    },
    /**
     * 配置编辑器
     */
    configurationEditor() {
      this.editor = new Editor(`#${this.editorId}`);

      if (!this.isPreviewContent) {
        // 配置菜单
        this.editor.config.menus = [
          "head",
          "bold",
          "fontSize",
          "fontName",
          "italic",
          "underline",
          "strikeThrough",
          // "indent",
          "lineHeight",
          "foreColor",
          "backColor",
          "link",
          "list",
          "justify",
          "quote",
          "emoticon",
          "image",
          "video",
          "table",
          "code",
          "splitLine",
          "undo",
          "redo",
        ];

        if (this.uploadImgPath) this.editor.config.menus.splice(16, 0, "image");
        if (this.uploadVideoPath)
          this.editor.config.menus.splice(17, 0, "video");

        const menuKey = "textIndent"; // 给定菜单名
        this.editor.menus.extend(menuKey, AlertMenu);
        this.editor.config.menus = this.editor.config.menus.concat(menuKey);

        // 配置表情包
        this.editor.config.emotions = [
          {
            title: "qq表情",
            type: "image", // 'emoji' 或 'image' ，即 emoji 形式或者图片形式
            content: emojiJSON_qq,
          },
          {
            title: "新浪表情",
            type: "image", // 'emoji' 或 'image' ，即 emoji 形式或者图片形式
            content: emojiJSON_sina,
          },
        ];

        this.editor.config.placeholder = "请输入内容...";
        // this.editor.config.height = this.height;
        this.editor.config.zIndex = 10;

        // 上传图片配置 Begin
        this.editor.config.uploadImgServer = this.uploadImgPath || ""; // 上传图片地址
        this.editor.config.uploadImgMaxLength = 1; // 一次最多上传图片数量
        this.editor.config.uploadFileName = "file"; // 自定义filename --- 即自定义【formData.append(name, file) 】中的name
        this.editor.config.uploadImgMaxSize = 50 * 1024 * 1024; // 限制图片大小50M --- 默认5M
        // this.editor.config.uploadImgTimeout = 10 * 1000;  // 上传接口等待的最大时间 --- 默认10s
        // this.editor.config.uploadImgHeaders = this.headersParams(); // 设置请求头
        this.editor.config.uploadImgParams = {
          type: "3",
        }; // 请求参数
        this.editor.config.uploadImgHooks = {
          // // 上传图片之前
          before: (xhr) => {
            // this.editor.config.uploadImgHeaders = this.headersParams(); // 设置请求头
            // console.log('before', xhr);
            // // 可阻止图片上传
            // return {
            //   prevent: true,
            //   msg: '需要提示给用户的错误信息'
            // }
          },
          // 图片上传并返回了结果，图片插入已成功
          // success: function (xhr) {
          //   console.log('success', xhr);
          //   this.$message.success('图片上传成功!');
          // },
          success: (xhr) => {
            console.log("success", xhr);
            this.$message.success("图片上传成功!");
          },
          // 图片上传并返回了结果，但图片插入时出错了
          fail: (xhr, editor, resData) => {
            console.log("fail", xhr, editor, resData);
            this.$message.error("图片上传成功,但插入至编辑器失败，请稍后重试!");
          },
          // 上传图片出错，一般为 http 请求的错误
          error: (xhr, editor, resData) => {
            console.log("error", xhr, resData);
            this.$message.error("图片上传失败，请稍后重试!");
          },
          // 上传图片超时
          timeout: (xhr) => {
            console.log("upload-img-timeout");
            this.$message.error("上传图片超时，请稍后重试!");
          },
          // // 图片上传并返回了结果，想要自己把图片插入到编辑器中
          // // 例如服务器端返回的不是 { errno: 0, data: [...] } 这种格式，可使用 customInsert
          customInsert: (insertImgFn, result) => {
            // 添加此方法，上传成功后的图片将不会自动插入编辑器中，即：不会执行success
            // result 即服务端返回的接口
            if (result.code == 200) {
              console.log("customInsert========", result);
              const url = result.data.replace(
                "/home/digitrpt/html/images/",
                "http://132.98.83.22:8088/images/"
              );

              // insertImgFn 可把图片插入到编辑器，传入图片 src ，执行函数即可
              insertImgFn(url);
            } else {
              this.$message.error(result.msg);
            }
          },
        };
        this.editor.config.showLinkImg = false; // 隐藏插入网络图片功能
        // 上传图片配置 End

        // 上传视频配置 Begin
        this.editor.config.uploadVideoServer = this.uploadVideoPath || ""; // 上传视频地址
        this.editor.config.uploadVideoName = "file"; // 自定义filename --- 即自定义【formData.append(name, file) 】中的name
        this.editor.config.uploadVideoMaxSize = 50 * 1024 * 1024; // 限制视频大小50M
        // this.editor.config.uploadImgTimeout = 10 * 1000;  // 上传接口等待的最大时间 --- 默认10s
        this.editor.config.uploadVideoHeaders = this.headersParams(); // 设置请求头
        this.editor.config.uploadVideoParams = {
          type: "7",
        }; // 请求参数

        let loadingInstance = null;
        this.editor.config.uploadVideoHooks = {
          // // 上传视频之前

          before: (xhr) => {
            this.editor.config.uploadVideoHeaders = this.headersParams(); // 设置请求头
            console.log("before", xhr);
            loadingInstance = Loading.service({
              lock: true,
              text: "正在上传中",
              background: "rgba(0, 0, 0, 0.7)",
            });

            // // 可阻止视频上传
            // return {
            //   prevent: true,
            //   msg: '需要提示给用户的错误信息'
            // }
          },
          // 视频上传并返回了结果，视频插入已成功
          // success: function (xhr) {
          //   console.log('success', xhr);
          //   this.$message.success('视频上传成功!');
          // },
          success: (xhr) => {
            loadingInstance.close();
            console.log("success", xhr);
            this.$message.success("视频上传成功!");
          },
          // 视频上传并返回了结果，但视频插入时出错了
          fail: (xhr, editor, resData) => {
            loadingInstance.close();
            console.log("fail", xhr, editor, resData);
            this.$message.error("视频上传成功,但插入至编辑器失败，请稍后重试!");
          },
          // 上传视频出错，一般为 http 请求的错误
          error: (xhr, editor, resData) => {
            loadingInstance.close();
            console.log("error", xhr, resData);
            this.$message.error("视频上传失败，请稍后重试!");
          },
          // 上传视频超时
          timeout: (xhr) => {
            loadingInstance.close();
            console.log("upload-img-timeout");
            this.$message.error("上传视频超时，请稍后重试!");
          },
          // // 视频上传并返回了结果，想要自己把视频插入到编辑器中
          // // 例如服务器端返回的不是 { errno: 0, data: [...] } 这种格式，可使用 customInsert
          customInsert: (insertVideoFn, result) => {
            // 添加此方法，上传成功后的视频将不会自动插入编辑器中，即：不会执行success
            // result 即服务端返回的接口
            // let resData = null;
            // // const encryptData = sm2Decrypt(result.data);
            // const encryptData = result.data;
            // try {
            //   resData = JSON.parse(encryptData);
            // } catch (err) {
            //   resData = encryptData;
            // }
            // result.data = resData;
            console.log("customInsert========", result);
            // const url = result。

            // insertImgFn 可把视频插入到编辑器，传入视频 src ，执行函数即可
            // insertVideoFn(result.data);
            // loadingInstance.close();
            if (result.code == 200) {
              const url = result.data.replace(
                "/home/digitrpt/html/images/",
                "http://132.98.83.22:8088/images/"
              );
              insertVideoFn(url);
              loadingInstance.close();
            } else {
              this.$message.error(result.msg);
            }
          },
        };
        this.editor.config.showLinkVideo = false; // 隐藏插入网络视频功能
        // 上传视频配置 End
      } else {
        this.editor.config.menus = [];
      }
      this.editor.config.onchange = (newHtml) => {
        this.$emit("changeEditor", newHtml);
      };
      // 配置触发 onchange 的时间频率，默认为 200ms
      this.editor.config.onchangeTimeout = 500; // 修改为 500ms

      this.editor.create();
    },
  },
};
</script>

<style lang="scss" scoped></style>
